#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.

""" Convert (some) XML to Json. 
    Not guaranteed to work for all documents.
"""
import xml.etree.ElementTree as ET

def XmlToJson(xml):
  tree = ET.fromstring(xml)
  obj = elementToObject(tree)
  return obj

def elementToObject(elem):
  obj = {}

  # Append attributes as python properties
  for key in elem.keys():
    obj[key] = elem.get(key)

  # Append text as the 'text' property
  if elem.text:
    obj['text'] = elem.text

  for child in elem.getchildren():
    # Is this a single child
    name = child.tag
    # Remove namespaces (embedded with James Clark's notation)
    if name[0] == '{':
      name = name[name.find('}') + 1:]

    # Form an approximate plural for repeated keys
    plural_name = name + 's'

    if obj.has_key(plural_name):
      obj[plural_name].append(elementToObject(child))
    elif (len(elem.findall(child.tag)) > 1):
      obj[plural_name] = []
      obj[plural_name].append(elementToObject(child))
    else:
      obj[name] = elementToObject(child)

  return obj
